package org.crud4j.validator.date;

import java.lang.annotation.Annotation;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.crud4j.validator.ValueValidator;
import org.crud4j.validator.ValueValidatorException;

public class DateValidator implements ValueValidator {

	private Date annotation;

	private SimpleDateFormat formatter;

	@SuppressWarnings("unchecked")
	public Class getAnnotationClass() {
		return Date.class;
	}

	public void init(Annotation annotation) {
		this.annotation = (Date) annotation;
		this.formatter = new SimpleDateFormat(this.annotation.pattern());
		this.formatter.setLenient(false);
	}

	public void validate(Object value) throws ValueValidatorException {
		if (String.class.isAssignableFrom(value.getClass())) {
			try {
				formatter.parse((String) value);
			} catch (ParseException e) {
				throw new ValueValidatorException(e.getMessage());
			}
		}
	}
}
